<script setup>
import {users} from '@/utils/data.js'
import MetaTable from "@/components/MetaTable.vue"
import {nanoid} from "nanoid"
import store, {templateMapping} from '@/utils/store.js'
import MetaIcon from "@/components/MetaIcon.vue";
import {renderTemplate, typeMapping} from "@/utils/tool.js";
import {useClipboard} from "@vueuse/core";
import {ElMessage} from "element-plus";
import {cloneDeep} from 'lodash'
import TemplateRender from "./TemplateRender.vue";

users.forEach(user => {user.id = nanoid()})
const data = reactive(users)
const cols = reactive([
  {type: 'input'    , label: '注释', prop: 'columnComment'   , width: '200'},
  {type: 'input'    , label: '列名', prop: 'columnName'      , width: '200'},
  {type: 'input'    , label: '类型', prop: 'columnType'      , width: '140', /*input: {formatter: v => v?.toUpperCase()}*/},
  {type: 'checkbox' , label: '主键', prop: 'isPrimary'       , width: '50' , align: 'center'},
  {type: 'checkbox' , label: '非空', prop: 'isNonNull'       , width: '50' , align: 'center'},
  {type: 'checkbox' , label: '自增', prop: 'isAutoIncrement' , width: '50' , align: 'center'},
  {type: 'input'    , label: '默认', prop: 'columnDefault'   , width: '100'},
  {type: 'input'    , label: '说明', prop: 'remark'          , showOverflowTooltip: true},
])

const form = reactive({
  tableComment: '用户表',
  tableName: 'sys_user',
  database: 'postgres',
  typeMapping: false,
})
const rules = reactive({
  tableComment: [{required: true, message: '请输入表注释'}, {max: 256, message: '最大长度为256位'}],
  tableName   : [{required: true, message: '请输入表名称'}, {max: 256, message: '最大长度为256位'}],
  database    : [{required: true, message: '请选择数据库类型'}],
})

const {copy} = useClipboard({ legacy: true})
const formRef = useTemplateRef('formRef')

const templateData = computed(() => {
  const columns = cloneDeep(data)
  if (form.typeMapping) {
    columns.forEach(c => c.columnType = typeMapping(c.columnType, form.database, true))
  }
  return { tableComment: form.tableComment, tableName: form.tableName, columns}
})

// 快速创建表
function quickTable() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const key = 'database-' + form.database + '-CreateTable'
      const template = templateMapping.value.get(key)
      const result = renderTemplate(template, templateData.value)
      await copy(result)
      ElMessage({message: 'SQL复制成功', type: 'success'})
    }
  })
}

// 显示生成代码
const moreDialog = reactive({
  visible: false
})
function showMoreCode() {
  moreDialog.visible = true
}
</script>

<template>
  <meta-table :data :cols color-property="columnType"
              show-header show-move-btn show-tool-btn allow-add-row>
      <el-form ref="formRef" :model="form" :rules="rules" inline >
        <el-form-item label="表注释" prop="tableComment">
          <el-input v-model="form.tableComment" input-style="color: var(--el-color-danger)"></el-input>
        </el-form-item>
        <el-form-item label="表名称" prop="tableName">
          <el-input v-model="form.tableName" input-style="color: var(--el-color-primary)"></el-input>
        </el-form-item>
        <el-form-item label="数据库" prop="database">
          <el-select v-model="form.database" style="width: 140px">
            <el-option v-for="item in store.databases" :value="item">
              <MetaIcon :name="item"></MetaIcon>
            </el-option>
            <template #label>
              <MetaIcon :name="form.database"></MetaIcon>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="类型映射">
          <el-checkbox v-model="form.typeMapping"></el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button icon="el-icon-magic-stick" type="primary" @click="quickTable">建表</el-button>
            <el-button icon="el-icon-memo" type="danger" @click="showMoreCode">扩展</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
  </meta-table>

  <el-dialog title="模板渲染" v-model="moreDialog.visible" width="80vw" draggable overflow destroy-on-close align-center>
    <TemplateRender :data="templateData" :style="{height: '70vh'}"/>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.el-form-item) {
  // 表单下方不留空白
  margin-bottom: 0;
  margin-right: 10px;

  // 校验的错误信息显示在input框里面即可
  .el-form-item__error {
    top: unset;
    left: 10px;
  }
}
</style>